package com.apache.common.plugins;

import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname RuleTempSyncExamplePluginImpl
 * @Description 规则模板值同步到实例
 * @Date 2021/1/11 11:16
 * @Created by fpc
 */
public class RuleTempSyncExamplePluginImpl implements CustomMethodPlugin {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Override
    public Object beforeInvoke(Map<String, Object> map) {
        return null;
    }

    @Override
    public Object doInvoke(Map<String, Object> map) {
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {
        List<Map> configList = new ArrayList<>();
        String sysRuleNo = String.valueOf(map.get("ruleNo"));
        if(StrUtil.isNull(sysRuleNo)){
            String w_sysRuleNo = String.valueOf(map.get("sysParamConf.w_sysRuleNo"));
            sysRuleNo=w_sysRuleNo;
        }
        String w_sourceType = String.valueOf(map.get("sysParamConf.w_sourceType"));
        String rulesType = String.valueOf(map.get("rulesType"));


        //模板修改,同步prod
        if(StrUtil.isNotNull(sysRuleNo)&&"temp".equals(w_sourceType)){
            rulesType = String.valueOf(map.get("sysRulesTemplate.rulesType"));
            Map<String,Object> w_exampleMap = new HashMap<>();
            w_exampleMap.put("sysParamConf.w_sourceType","example");
            w_exampleMap.put("sysParamConf.w_sysRuleNo",sysRuleNo);
            ResultEntity exampleCountEntity = IusPluginUtil.getInstance().select("plateform","count", "s_sysParamConf", w_exampleMap);
            if(!Validator.isEmpty(exampleCountEntity)&&!Validator.isEmpty(exampleCountEntity.getEntity())) {
                Long exampleCount = (Long) exampleCountEntity.getEntity();
                if(exampleCount>0){
                    Map<String,Object> w_tempConfMap = new HashMap<>();
                    w_tempConfMap.put("sysParamConf.w_sourceType","temp");
                    w_tempConfMap.put("sysParamConf.w_sysRuleNo",sysRuleNo);
                    ResultEntity resultEntity2 = IusPluginUtil.getInstance().select("plateform","list", "s_sysParamConf", w_tempConfMap);
                    if(!Validator.isEmpty(resultEntity2)&&!Validator.isEmpty(resultEntity2.getEntity())){
                        configList=(List)resultEntity2.getEntity();
                    }
                    if(configList.size()<=0){//删除模板不存在的对应实例及映射关系
                        Map<String,Object> d_whereMap = new HashMap<>();
                        d_whereMap.put("sysParamConf.w_sysRuleNo",sysRuleNo);
                        d_whereMap.put("sysRulesProd.w_rulesNo",sysRuleNo);
                        ResultEntity d_resultEntity = IusPluginUtil.getInstance().saveInvoke("plateform", "d_sysParamConf,d_sysRulesProd", d_whereMap);
                        log.info("删除模板不存在的情况下的配置及对应实例d_resultEntity:"+d_resultEntity.toString());
                        return null;
                    }
                    String nodeIds="",paramJuds="",paramVals="",ub_confSysRuleNo="",sourceType="";
                    for (Map configMap:configList) {
                        if("item".equals(String.valueOf(configMap.get("nodeType")))){
                            nodeIds+=configMap.get("nodeId")+"-#-";
                            paramJuds+=configMap.get("paramJud")+"-#-";
                            paramVals+=configMap.get("paramVal")+"-#-";
                            ub_confSysRuleNo+=sysRuleNo+"-#-";
                            sourceType+="example-#-";
                        }
                    }
                    if(nodeIds.indexOf("-#-")==-1){
                        return null;
                    }
                    nodeIds=nodeIds.substring(0,nodeIds.length()-3);
                    paramJuds=paramJuds.substring(0,paramJuds.length()-3);
                    paramVals=paramVals.substring(0,paramVals.length()-3);
                    ub_confSysRuleNo=ub_confSysRuleNo.substring(0,ub_confSysRuleNo.length()-3);
                    sourceType=sourceType.substring(0,sourceType.length()-3);
                    Map<String,Object> w_ubMap = new HashMap<>();
                    w_ubMap.put("sysParamConf.w_nodeId",nodeIds);
                    w_ubMap.put("sysParamConf.w_sourceType",sourceType);
                    w_ubMap.put("sysParamConf.w_sysRuleNo",ub_confSysRuleNo);
                    w_ubMap.put("sysParamConf.paramJud",paramJuds);
                    w_ubMap.put("sysParamConf.paramVal",paramVals);
                    w_ubMap.put("ifBatch","T");//启用-批量操作
                    w_ubMap.put("sysParamConf.splitAttr","w_nodeId");//指定批量数据分割属性名，且参数中必须有
                    ResultEntity resultEntity = IusPluginUtil.getInstance().saveInvoke("plateform", "ub_sysParamConf", w_ubMap);
                    log.info("修改模板规则项同步conf表返回值：resultEntity=========="+resultEntity.toString());
                    if(!Validator.isEmpty(resultEntity)&&"操作成功".equals(resultEntity.getMessage())) {
                        w_exampleMap.put("sysParamConf.w_sourceType", "example");
                        w_exampleMap.put("sysParamConf.w_sysRuleNo", sysRuleNo);
                        ResultEntity exampleListEntity = IusPluginUtil.getInstance().select("plateform", "list", "s_sysParamConf", w_exampleMap);
                        if (!Validator.isEmpty(exampleListEntity) && !Validator.isEmpty(exampleListEntity.getEntity())) {
                            List<Map>  exampleList = (List<Map>) exampleListEntity.getEntity();
                            Map<String, List<Map>> tempMap = new HashMap<>();
                            for (Map exampleData : exampleList) {
                                String deviceId = String.valueOf(exampleData.get("sysParamId"));
                                if (tempMap.containsKey(deviceId)) {
                                    List<Map> deviceGroupList = tempMap.get(deviceId);
                                    deviceGroupList.add(exampleData);
                                } else {
                                    List<Map> tempList = new ArrayList<>();
                                    tempList.add(exampleData);
                                    tempMap.put(deviceId, tempList);
                                }
                            }
                            Map<String, Object> w_ubProdMap = new HashMap<>();
                            String deviceIds = "";
                            String inRuleStrs = "",outRuleStrs="";
                            String ub_prodSysRuleNos = "";
                            if("deviceWarn".equals(rulesType)){
                                String dealType=String.valueOf(map.get("sysRulesTemplate.nodeType"));
                                String constantStatus=String.valueOf(map.get("sysRulesTemplate.nodeStatus"));
                                w_ubProdMap.put("sysRulesProd.dealType",dealType);
                                w_ubProdMap.put("sysRulesProd.constantStatus",constantStatus);
                                for (String key : tempMap.keySet()) {
                                    List<Map> confList = tempMap.get(key);
                                    List<Map> conftreeList = builTree(confList);
                                    String inRuleStr = getRuleStr(conftreeList);
                                    deviceIds += key + "-#-";
                                    inRuleStrs += inRuleStr + "-#-";
                                    ub_prodSysRuleNos += sysRuleNo + "-#-";
                                }
                            }else if("deviceLinkageControl".equals(rulesType)){
                                for (String key : tempMap.keySet()) {
                                    List<Map> confList = tempMap.get(key);
                                    List<Map> conftreeList = builTree(confList);
                                    String inRuleStr = getRuleStr(conftreeList);
                                    String outRuleStr = getRuleStr(conftreeList);
                                    deviceIds += key + "-#-";
                                    inRuleStrs += inRuleStr + "-#-";
                                    outRuleStrs += outRuleStr + "-#-";
                                    ub_prodSysRuleNos += sysRuleNo + "-#-";
                                }
                                outRuleStrs = outRuleStrs.substring(0, outRuleStrs.length() - 3);
                                w_ubProdMap.put("sysRulesProd.formulaCal", outRuleStrs);

                            }

                            deviceIds = deviceIds.substring(0, deviceIds.length() - 3);
                            inRuleStrs = inRuleStrs.substring(0, inRuleStrs.length() - 3);
                            ub_prodSysRuleNos = ub_prodSysRuleNos.substring(0, ub_prodSysRuleNos.length() - 3);

                            w_ubProdMap.put("sysRulesProd.w_cateId", deviceIds);
                            w_ubProdMap.put("sysRulesProd.w_ruleNo", ub_prodSysRuleNos);
                            w_ubProdMap.put("sysRulesProd.formulaSrc", inRuleStrs);
                            w_ubProdMap.put("sysRulesProd.modifyTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
                            w_ubProdMap.put("sysRulesProd.formulaDesc", String.valueOf(map.get("sysRulesTemplate.formulaDesc")));


                            w_ubProdMap.put("ifBatch", "T");//启用-批量操作
                            w_ubProdMap.put("sysRulesProd.splitAttr", "w_cateId");//指定批量数据分割属性名，且参数中必须有
                            ResultEntity resultEntity1 = IusPluginUtil.getInstance().saveInvoke("plateform", "ub_sysRulesProd", w_ubProdMap);
                            log.info("修改prod表规则字符串返回值：resultEntity1==========" + resultEntity1.toString());
                        }
                    }
                }
            }
        }else{//设备添加规则时，同步prod

            String modelTypes = String.valueOf(map.get("modelTypes"));
            String deviceId = String.valueOf(map.get("sysParamConf.sysParamId"));
            String inRuleStr=null,outRuleStr=null;
            if(modelTypes.startsWith("d_")){
                deviceId = String.valueOf(map.get("sysParamConf.w_sysParamId"));
            }
            Map<String,Object> w_exampleMap = new HashMap<>();
            w_exampleMap.put("sysParamConf.w_sourceType","example");
            w_exampleMap.put("sysParamConf.w_sysRuleNo",sysRuleNo);
            w_exampleMap.put("sysParamConf.w_sysParamId",deviceId);
            ResultEntity resultEntity2 = IusPluginUtil.getInstance().select("plateform","list", "s_sysParamConf", w_exampleMap);
            if(!Validator.isEmpty(resultEntity2)&&!Validator.isEmpty(resultEntity2.getEntity())){
                configList=(List)resultEntity2.getEntity();
            }
            if(configList.size()<=0){//如果不存在模板删除对应关系，以及修改实例prod表
                Map<String,Object> d_whereMap = new HashMap<>();
                d_whereMap.put("sysParamConf.w_sysRuleNo",sysRuleNo);
                d_whereMap.put("sysRulesProd.w_rulesNo",sysRuleNo);
                ResultEntity d_resultEntity = IusPluginUtil.getInstance().saveInvoke("plateform", "d_sysParamConf,d_sysRulesProd", d_whereMap);
                log.info("删除模板不存在的情况下的配置及对应实例d_resultEntity:"+d_resultEntity.toString());
                return null;
            }
            if("deviceLinkageControl".equals(rulesType)) {
                List<Map> inConfigList = new ArrayList<>();
                List<Map> outConfigList = new ArrayList<>();
                for (Map map1 : configList) {
                    if("in".equals(String.valueOf(map1.get("ifSubParam")))){
                        inConfigList.add(map1);
                    }else {
                        outConfigList.add(map1);
                    }
                }
                List<Map> inConftreeList = builTree(inConfigList);
                inRuleStr = getRuleStr(inConftreeList);
                List<Map> outConftreeList = builTree(outConfigList);
                outRuleStr = getRuleStr(outConftreeList);

            }else{
                List<Map> conftreeList = builTree(configList);
                inRuleStr = getRuleStr(conftreeList);
            }
            Map<String,Object> saveProdMap = new HashMap<>();
            if(modelTypes.startsWith("d_")){//设备修改规则项
                saveProdMap.put("sysRulesProd.w_cateId",deviceId);
                saveProdMap.put("sysRulesProd.w_rulesno",sysRuleNo);
                saveProdMap.put("sysRulesProd.formulaSrc", inRuleStr);
                if("deviceWarn".equals(rulesType)){
                    String dealType=String.valueOf(map.get("nodeType"));
                    String constantStatus=String.valueOf(map.get("nodeStatus"));
                    saveProdMap.put("sysRulesProd.dealType",dealType);
                    saveProdMap.put("sysRulesProd.constantStatus",constantStatus);
                }else if("deviceLinkageControl".equals(rulesType)){
                    saveProdMap.put("sysRulesProd.formulaCal", outRuleStr);
                }
                ResultEntity resultEntity1 = IusPluginUtil.getInstance().saveInvoke("plateform", "u_sysRulesProd", saveProdMap);
                log.info("修改prod表返回值：resultEntity1=========="+resultEntity1.toString());
            }else {//设备新增规则
                String deviceNo = String.valueOf(map.get("deviceNo"));
                String deviceCname = String.valueOf(map.get("deviceCname"));
                String rulesName = String.valueOf(map.get("rulesName"));
                String formulaDesc = String.valueOf(map.get("formulaDesc"));
                if("deviceWarn".equals(rulesType)){
                    String dealType=String.valueOf(map.get("nodeType"));
                    String constantStatus=String.valueOf(map.get("nodeStatus"));
                    saveProdMap.put("sysRulesProd.dealType",dealType);
                    saveProdMap.put("sysRulesProd.constantStatus",constantStatus);
                }else if("deviceLinkageControl".equals(rulesType)){
                    saveProdMap.put("sysRulesProd.formulaCal", outRuleStr);
                }
                saveProdMap.put("sysRulesProd.cateId",deviceId);
                saveProdMap.put("sysRulesProd.cateName",deviceCname);
                saveProdMap.put("sysRulesProd.cateNo",deviceNo);
                saveProdMap.put("sysRulesProd.createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
                saveProdMap.put("sysRulesProd.delStatus", "F");
                saveProdMap.put("sysRulesProd.rulesName", rulesName);
                saveProdMap.put("sysRulesProd.rulesNo", sysRuleNo);
                saveProdMap.put("sysRulesProd.formulaSrc", inRuleStr);
                saveProdMap.put("sysRulesProd.sysName", "flc");
                saveProdMap.put("sysRulesProd.formulaDesc", formulaDesc);
                saveProdMap.put("sysRulesProd.rulesType", rulesType);
                ResultEntity resultEntity3 = IusPluginUtil.getInstance().saveInvoke("plateform", "i_sysRulesProd", saveProdMap);
                log.info("新增prod表返回值：resultEntity2=========="+resultEntity3.toString());
            }
        }
        return null;
    }
    //构建规则数据公式
    private String getRuleStr(List<Map> list){
        String ruleStr = "(";
        for (Map dataMap:list) {
            String str="";
            if("group".equals(dataMap.get("nodeType"))){
                str = String.valueOf(dataMap.get("paramRef")).trim().replaceAll(" ",getRuleStr((List<Map>)dataMap.get("children")));
                ruleStr+=str;
            }else{
                ruleStr+=str+dataMap.get("paramRef")+ "{{"+dataMap.get("paramKey")+"}}"+dataMap.get("paramJud")+dataMap.get("paramVal");
            }
        }

        return ruleStr+")";
    }



    //建立树形结构
    private List<Map> builTree(List<Map> menuList){
        List<Map> treeMenus =new  ArrayList<Map>();
        for(Map menuNode : getRootNode(menuList)) {
            menuNode=buildChilTree(menuNode, menuList);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private Map buildChilTree(Map pNode,List<Map> menuList){
        List<Map> chilMenus =new  ArrayList<Map>();
        for(Map menuNode : menuList) {
            if(menuNode.get("fatherId").equals(pNode.get("nodeId"))) {
                chilMenus.add(buildChilTree(menuNode,menuList));
            }
        }
        pNode.put("children",chilMenus);
        return pNode;
    }

    //获取根节点
    private List<Map> getRootNode(List<Map> menuList) {
        List<Map> rootMenuLists =new  ArrayList<Map>();
        for(Map menuNode : menuList) {
            if("0".equals(menuNode.get("fatherId"))) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

}
